package com.soc.course.controller;

import com.soc.auth.domain.dto.ClassMemberPageQuery;
import com.soc.auth.domain.entity.Class;
import com.soc.auth.domain.vo.ClassMemberVO;
import com.soc.auth.domain.vo.PageVO;
import com.soc.auth.service.ClassService;
import com.soc.auth.utils.ResultResponse;
import com.soc.course.controller.util.R;
import com.soc.course.sercice.ChapterService;
import com.soc.course.sercice.TaskUserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @ClassName classController
 * @Description ToDo
 * @Author hjy
 * @Date 2023/7/3 22:33
 **/
@RestController
public class classTaskController {

    @Autowired
    private ClassService classService;
    @Autowired
    private TaskUserService taskUserService;

    @Autowired
    private ChapterService chapterService;

    @Value("${file.path}")
    private String filePath;


    /**
     * 查询班级下的所有成员
     *
     * @param queryParams 查询条件
     * @return 查询结果
     */
    @GetMapping("/class/listClassMemberPages")
    public ResultResponse<PageVO<ClassMemberVO>> listClassMemberPages(@Valid ClassMemberPageQuery queryParams) {

        PageVO<ClassMemberVO> classMemberVOPageVO = classService.listClassMemberPages(queryParams);

        Map<String, Long> userFinshTask = taskUserService.getUserFinshTask(String.valueOf(queryParams.getCourseId()), String.valueOf(queryParams.getClassId()));

        Integer courseTotalTask = chapterService.getCourseTask(queryParams.getCourseId());
        for (ClassMemberVO classMemberVO : classMemberVOPageVO.getRecords()) {
            Long userFinshedTask = userFinshTask.getOrDefault(classMemberVO.getNo(), 0L);
//            Long userFinshedTask = userFinshTask.get("1730231203186880514");
            classMemberVO.setUserTaskCount(String.valueOf(userFinshedTask) + "/" + String.valueOf(courseTotalTask));
        }
        return ResultResponse.success(classMemberVOPageVO);
    }

    @RequestMapping("/class/export")
    public void fileDownLoad(HttpServletResponse response, @Valid ClassMemberPageQuery queryParams) {
        queryParams.setPageSize(-1);
        PageVO<ClassMemberVO> classMemberVOPageVO = classService.listClassMemberPages(queryParams);
        Class classObj = classService.getById(queryParams.getClassId());
        Map<String, Long> userFinshTask = taskUserService.getUserFinshTask(String.valueOf(queryParams.getCourseId()), String.valueOf(queryParams.getClassId()));
        Integer courseTotalTask = chapterService.getCourseTask(queryParams.getCourseId());
        for (ClassMemberVO classMemberVO : classMemberVOPageVO.getRecords()) {
            Long userFinshedTask = userFinshTask.getOrDefault(classMemberVO.getNo(), 0L);
            classMemberVO.setUserTaskCount(userFinshedTask + "/" + courseTotalTask);
        }
        int rowNum = 1;
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Class Members");

// Create header row
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("学号");
        headerRow.createCell(1).setCellValue("真实姓名");
        headerRow.createCell(2).setCellValue("是否绑定");
        headerRow.createCell(3).setCellValue("任务完成数");
        List<ClassMemberVO> classMemberVOList = classMemberVOPageVO.getRecords();
        for (ClassMemberVO classMemberVO : classMemberVOList) {
            Row dataRow = sheet.createRow(rowNum++);
            dataRow.createCell(0).setCellValue(classMemberVO.getNo());
            dataRow.createCell(1).setCellValue(classMemberVO.getRealName());
            Cell isCertificationCell = dataRow.createCell(2);
            if (classMemberVO.getIsCertification() == 0) {
                isCertificationCell.setCellValue("未绑定");
            } else if (classMemberVO.getIsCertification() == 1) {
                isCertificationCell.setCellValue("已绑定");
            }
            dataRow.createCell(3).setCellValue(classMemberVO.getUserTaskCount());
        }

// Auto-size columns
        for (int i = 0; i < 4; i++) {
            sheet.autoSizeColumn(i);
        }

// Convert workbook to byte array
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
// Set response headers
        String fileName = classObj.getName() + ".xlsx";
        try {
            String fileNameEncoder = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename="+fileNameEncoder );
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

// Write byte array content to response output stream
        try {
            response.getOutputStream().write(outputStream.toByteArray());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping("/class/download/example")
    public String getClassImportExample(HttpServletResponse response, @RequestParam String fileName){
        File file = new File(filePath+"/"+fileName);
        response.reset();
//        response.setContentType("application/octet-stream");
//        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        try {
            String fileNameEncoder = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNameEncoder);
        } catch (UnsupportedEncodingException e) {
           return  "{\"code\":0;\"msg\":\"下载失败\"}";
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
//            return new R(0,"下载失败");
            return  "{\"code\":0;\"msg\":\"下载失败\"}";
        }
//        return new R(200,"下载成功");
        return  "{\"code\":0;\"msg\":\"下载失败\"}";
    }

}
